<template>
  <div class=" flex">
    <!-- 左侧登录表单 -->
    <div class="flex-1 flex items-center justify-center bg-gray-50">
      <div class="max-w-md w-full space-y-8 p-8">
        <div class="text-center">
          <h2 class="text-3xl font-bold text-gray-900 mb-8">Welcome Back!</h2>
        </div>
        
        <form class="space-y-6" @submit.prevent="handleLogin">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
              Username:
            </label>
            <input
              id="username"
              v-model="username"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="Enter your username"
            />
          </div>
          
          <div>
            <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
              Password:
            </label>
            <input
              id="password"
              v-model="password"
              type="password"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="Enter your password"
            />
          </div>
          
          <button
            type="submit" style="background-color: #0066a1;"
            class="w-full cursor-pointer  text-white py-3 px-4 rounded-full hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition duration-200 font-medium"
          >
            Login
          </button>
        </form>
        
        <div class="text-center">
          <p class="text-gray-600">
            Dont have and account? 
            <NuxtLink to="/register" class="text-blue-600 hover:text-blue-500 font-medium">Register</NuxtLink>
          </p>
          <!-- <p class="text-gray-600 mt-2">
            <NuxtLink to="/test-google-login" class="text-blue-600 hover:text-blue-500 font-medium">测试Google登录</NuxtLink>
            |
            <NuxtLink to="/login-simple" class="text-blue-600 hover:text-blue-500 font-medium">简化Google登录</NuxtLink>
          </p> -->
        </div>
        
        <!-- 分割线 -->
        <div class="relative">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300"></div>
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-gray-50 text-gray-500">Or continue with</span>
          </div>
        </div>
        
        <!-- Google登录按钮 -->
        <div class="text-center">
          <button
            type="button"
            id="google-login-btn"
            class="inline-flex cursor-pointer items-center justify-center w-full px-4 py-3 border border-gray-300 rounded-full bg-white text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition duration-200 font-medium"
            @click="handleGoogleLogin"
          >
            <svg class="w-5 h-5 mr-3" viewBox="0 0 24 24">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
            Continue with Google
          </button>
        </div>
      </div>
    </div>
    <!-- 右侧蓝色背景 -->
    <div style="background-color: #0066a1;width: 40vw;">
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { userApi } from '~/public/utils/api'
import { useLoginDialog } from '~/composables/useLoginDialog'
const runtimeConfig = useRuntimeConfig()

const username = ref('')
const password = ref('')

// Google OAuth configuration (use runtime config + current origin)
const GOOGLE_CLIENT_ID ='420168086989-flb4p9l7cbt1i9iqldqq08o2fqec4bmf.apps.googleusercontent.com'
const GOOGLE_REDIRECT_URI = typeof window !== 'undefined' ? `https://cbam.hongyuan3e.com/auth/google/callback` : ''

const handleLogin = async () => {
  try {
    // Step 1: Call login API
    const result = await userApi.login({
      userName: username.value,
      password: password.value
    })
    
    console.log('Login successful:', result)
    
    // Step 2: Store token and get complete user info
    if (result.data && result.data.token) {
      // Store token first (required for getUserInfo API)
      localStorage.setItem('token', result.data.token)
      
      // Step 3: Get complete user information
      try {
        const userInfoResult = await userApi.getUserInfo()
        
        if (userInfoResult.data) {
          // Step 4: Use complete user info for login
          const { $auth } = useNuxtApp()
          $auth.login({
            id: result.data.memberId,
            fullName: userInfoResult.data.fullName || username.value,
            name: username.value,
            email: userInfoResult.data.email || username.value,
            position: userInfoResult.data.position,
            phone: userInfoResult.data.phone,
            companyName: userInfoResult.data.companyName,
            companyAddress: userInfoResult.data.companyAddress
          }, result.data.token)
        }
      } catch (userInfoError) {
        console.error('Failed to get user info:', userInfoError)
        // Fallback: use basic info if getUserInfo fails
        const { $auth } = useNuxtApp()
        $auth.login({
          id: result.data.memberId,
          fullName: username.value,
          name: username.value,
          email: username.value
        }, result.data.token)
      }
    }
    
    const { $toast } = useNuxtApp()
    $toast.success('Login successful!')
    
    // Redirect to user page after successful login
    await navigateTo('/user')
  } catch (error) {
    console.error('Login failed:', error)
    const { $toast } = useNuxtApp()
    $toast.error(`Login failed: ${error.message}`)
  }
}

const handleGoogleLogin = () => {
  const googleAuthUrl = `https://cbam.hongyuan3e.com/prod-api/api/auth/render?redirect_uri=https://cbam.hongyuan3e.com/auth/google/callback`;
  window.location.href = googleAuthUrl;
  // Google OAuth 2.0 login flow
  // const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
  //   `client_id=${encodeURIComponent(GOOGLE_CLIENT_ID)}&` +
  //   `redirect_uri=${encodeURIComponent(GOOGLE_REDIRECT_URI)}&` +
  //   `response_type=code&` +
  //   `scope=${encodeURIComponent('openid email profile')}&` +
  //   `access_type=offline&` +
  //   `prompt=consent`
  
  // // Redirect to Google authorization page
  // window.location.href = googleAuthUrl
}

// Check if there's an authorization code in the URL
const checkAuthCode = () => {
  const urlParams = new URLSearchParams(window.location.search)
  const code = urlParams.get('code')
  
  if (code) {
    // If there's an authorization code, call backend API to exchange for access token
    exchangeCodeForToken(code)
  }
}

const exchangeCodeForToken = async (code) => {
  try {
    const { $auth } = useNuxtApp()
    
    // Call backend API to exchange access token
    const response = await $fetch('/api/auth/google', {
      method: 'POST',
      body: {
        code,
        redirect_uri: GOOGLE_REDIRECT_URI
      }
    })
    
    if (response.success) {
      // Use auth plugin to login
      $auth.login(response.user, response.token)
      
      // Redirect to home page
      await navigateTo('/')
    }
  } catch (error) {
    console.error('Google login error:', error)
    const { $toast } = useNuxtApp()
    $toast.error('Google login failed, please try again')
  }
}

onMounted(() => {
  // 自动重定向逻辑
  const route = useRoute()
  const redirect = route.query.redirect
  
  // 重定向到首页
  navigateTo('/')
  
  // 打开登录弹窗
  const { showLoginDialog } = useLoginDialog()
  showLoginDialog('login', redirect)
})

// Set page title
useHead({
  title: 'Login - Carbon Tariff Platform',
  script: [
    {
      src: 'https://accounts.google.com/gsi/client',
      async: true,
      defer: true
    }
  ]
})
</script>